<script setup>
import { inplanListApi, inplanDeleteApi, inplanSendApi, inplanArriveApi } from '@/apis/reservation.js'
import { ref } from 'vue'
import { onReachBottom, onShow, onLoad, onPageScroll } from "@dcloudio/uni-app"
import ReservationList from '../components/ReservationList.vue'
import AddBtn from '@/components/AddBtn.vue'
import { logisticePlanStatus } from '@/apis/dict.js'
import { hasPermission } from '@/directives/permission'

// 设置滚动阈值，当滚动距离超过这个值时隐藏表单
const SCROLL_THRESHOLD = 50

const params = ref({
  pageNum: 1,
  pageSize: 10,
})
const inplanList = ref([])
// 标记是否为首次加载页面
let isFirstLoad = true
const loadStatus = ref({
  status: "loadmore",
  noMore: false,
  loading: false
})

onLoad(async () => {
  await getStatus()
  await getData()
  // 首次加载完成后设置标记为false
  isFirstLoad = false
})

onShow(async () => {
  if (isFirstLoad) return
  init()
  await getData()
})

const init = () => {
  params.value = {
    pageNum: 1,
    pageSize: 10,
  }
  loadStatus.value.noMore = false
  loadStatus.value.status = "loadmore"
  inplanList.value = []
}

const statusList = ref([])
const getStatus = async () => {
  const res = await logisticePlanStatus()
  statusList.value = res.data || []
}

const getData = async () => {
  if (loadStatus.value.noMore || loadStatus.value.loading) return
  loadStatus.value.loading = true
  loadStatus.value.status = "loading"
  try {
    const res = await inplanListApi(params.value)
    const { rows, total } = res
    const arr = rows.map(item => {
      const status = statusList.value.find(i => i.dictValue === item.status)
      return {
        ...item,
        statusStr: status.dictLabel
      }
    })
    if (params.value.pageNum === 1) {
      inplanList.value = arr
    } else {
      inplanList.value = [...inplanList.value, ...arr]
    }
    if (arr.length < params.value.pageSize || inplanList.value.length >= total) {
      loadStatus.value.noMore = true
      loadStatus.value.status = "nomore"
    } else {
      loadStatus.value.status = "loadmore"
    }
    params.value.pageNum++
  } catch {
    loadStatus.value.status = "loadmore"
  } finally {
    loadStatus.value.loading = false
  }
}

onReachBottom(() => {
  if (!loadStatus.value.noMore) {
    getData()
  }
})

const handlerDelete = (val) => {
  uni.showModal({
    title: '温馨提示',
    content: `确定要删除${val.planname}的数据吗?`,
    success: async res => {
      if (!res.confirm) return
      await inplanDeleteApi(val.id)
      inplanList.value = inplanList.value.filter(i => i.id !== val.id)
      uni.$u.toast("删除成功")
    }
  })
}

const handlerInplanForm = () => {
  uni.navigateTo({
    url: '/pages/reservation/inplan/form'
  })
}

const handlerEdit = (item) => {
  const data = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/reservation/inplan/form?data=${data}`
  })
}

const handlerAddGoods = (item) => {
  const data = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/reservation/inplanGoods/index?data=${data}`
  })
}

const handlerApprovals = (item) => {
  const data = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/reservation/inplan/approvalsForm?data=${data}`
  })
}

const handlerSendGoods = async (item) => {
  uni.showModal({
    title: '温馨提示',
    content: `确定要发货${item.planname}的数据吗?`,
    success: async res => {
      if (!res.confirm) return
      try {
        await inplanSendApi(item)
        uni.$u.toast("操作成功")
        const index = inplanList.value.findIndex(i => i.id === item.id)
        if (index !== -1) {
          const statusObj = statusList.value.find(i => i.dictValue === '4')
          const statusStr = statusObj ? statusObj.dictLabel : '完成'
          inplanList.value[index] = {
            ...inplanList.value[index],
            status: '4',
            statusStr: statusStr
          }
        }
      } catch (e) {
        uni.$u.toast(e.msg ?? "操作失败")
      }
    }
  })
}

const handlerCarArrive = async (item) => {
  uni.showModal({
    title: '温馨提示',
    content: `车辆是否确定到达?`,
    success: async res => {
      if (!res.confirm) return
      try {
        await inplanArriveApi(item)
        uni.$u.toast("操作成功")
        const index = inplanList.value.findIndex(i => i.id === item.id)
        if (index !== -1) {
          const statusObj = statusList.value.find(i => i.dictValue === '6')
          const statusStr = statusObj ? statusObj.dictLabel : '车辆已到达'
          inplanList.value[index] = {
            ...inplanList.value[index],
            status: '6',
            statusStr: statusStr
          }
        }
      } catch (e) {
        uni.$u.toast(e.msg ?? "操作失败")
      }
    }
  })

}

const handlerBtn = (type, item) => {
  if (!buttonActions[type]) {
    console.warn("未知按钮类型:", type)
    return
  }
  buttonActions[type](item)
}
const buttonActions = {
  edit: (item) => handlerEdit(item),
  delete: (item) => handlerDelete(item),
  addGoods: (item) => handlerAddGoods(item),
  approvals: (item) => handlerApprovals(item),
  sendGoods: (item) => handlerSendGoods(item),
  carArrive: (item) => handlerCarArrive(item),
}

// 添加切换表单显示状态的方法
const formData = ref({
  planName: '',
  beginDate: '',
  endDate: '',
})

// 添加一个响应式变量控制搜索表单的显示和隐藏
const isFormVisible = ref(false)
const expectDateShow = ref(false)
const toggleFormVisibility = () => {
  isFormVisible.value = !isFormVisible.value
}
const changeExpectDate = e => {
  formData.value.beginDate = e.startDate
  formData.value.endDate = e.endDate
  expectDateShow.value = false
}

const handlerSearch = () => {
  const { planName, beginDate, endDate } = formData.value
  init()
  params.value = {
    ...params.value,
    planname: planName,
    ['params[beginExpectdate]']: beginDate,
    ['params[endExpectdate]']: endDate,
  }
  getData()
}
const handlerReset = () => {
  formData.value = {
    planName: '',
    beginDate: '',
    endDate: '',
  }
  init()
  getData()
}


// 页面滚动时触发
onPageScroll((e) => {
  // 当滚动距离大于阈值且表单当前是显示状态时，隐藏表单
  if (e.scrollTop > SCROLL_THRESHOLD && isFormVisible.value) {
    isFormVisible.value = false
  }
})
</script>

<template>
  <view class="page_container">
    <u-sticky>
      <view class="search_container flex_sb" @click="toggleFormVisibility">
        <text>搜索内容</text>
        <view>
          {{ isFormVisible ? '收起' : '展开' }}
          <u-icon :name="isFormVisible ? 'arrow-up' : 'arrow-down'" size="20"></u-icon>
        </view>
      </view>
      <view class="sticky-form-container" v-show="isFormVisible">
        <u-form :model="formData" label-width="200" class="form-container">
          <u-form-item label="计划名称:">
            <u-input v-model="formData.planName" placeholder="请输入计划名称" class="search-input" />
          </u-form-item>
          <u-form-item label="预计到达时间:">
            <view v-if="!formData.beginDate" class="date-picker" @click="expectDateShow = true">请选预计到达时间</view>
            <view v-else @click="expectDateShow = true">{{ formData.beginDate }} - {{ formData.endDate }}</view>
          </u-form-item>
          <u-form-item>
            <view style="display: flex;justify-content: space-around;">
              <u-button type="primary" size="medium" @click="handlerSearch">搜索</u-button>
              <u-button type="default" size="medium" @click="handlerReset">重置</u-button>
            </view>
          </u-form-item>
        </u-form>
      </view>
    </u-sticky>
    <ReservationList :list="inplanList" type="inplan" :loadmoreStatus="loadStatus.status" @clickBtn="handlerBtn" />
    <AddBtn @click="handlerInplanForm" v-if="hasPermission('logistics:inplan:add')" />
  </view>
  <u-calendar v-model="expectDateShow" mode="range" @change="changeExpectDate"></u-calendar>
</template>


<style lang="scss" scoped>
.form-container {
  background: #fff;
  z-index: 99;
}

.search_container {
  height: 100rpx;
  padding: 0 20rpx;
  background: #fff;
  z-index: 99;
  font-size: $list-font-size;
}
</style>